﻿using Kevin.Comm.Utility;
using Senparc.Weixin.Helpers;
using Senparc.Weixin.MP.CommonAPIs;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace RiderShop.Mobile.Common.ThirdEntity
{
    public static class Utility
    {
        private const string baseUrl = "https://api.weixin.qq.com/sns/oauth2/";
        private static string appKey = "wxd6ba880532a24a07";
        private static string appSecret = "81b6dd2267333e6aad7aa788e4753043";

        public static string GetBody(string Url, Encoding Encoder)
        {
            string resultBody = "";
            WebClient myClient = new WebClient();
            myClient.Headers.Add("Accept: */*");
            myClient.Headers.Add("User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET4.0E; .NET4.0C; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; SE 2.X MetaSr 1.0)");
            myClient.Headers.Add("Accept-Language: zh-cn");
            myClient.Headers.Add("Content-Type: multipart/form-data");
            //myClient.Headers.Add("Accept-Encoding: gzip, deflate");
            myClient.Headers.Add("Cache-Control: no-cache");
            myClient.Encoding = Encoder;
            resultBody = myClient.DownloadString(Url);

            return resultBody;
        }

        /// <summary>
        /// 通过GET得到API返回的数据
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="encode">编码方式</param>
        /// <param name="timeout">超时时间</param>
        /// <returns>返回的数据</returns>
        public static string GetBody(string url, Encoding encode, int timeout = 0)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "GET";
            if (timeout > 0)
            {
                webRequest.Timeout = timeout;
            }

            //接收返回信息
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), encode);

            return streamReader.ReadToEnd();
        }

        public static string PostBody(string Url, string body, Encoding Encoder)
        {
            string resultBody = "";
            WebClient myClient = new WebClient();
            myClient.Headers.Add("Accept: */*");
            myClient.Headers.Add("User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET4.0E; .NET4.0C; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; SE 2.X MetaSr 1.0)");
            myClient.Headers.Add("Accept-Language: zh-cn");
            myClient.Headers.Add("Content-Type: text/plain");
            myClient.Encoding = Encoder;

            byte[] postData = Encoding.UTF8.GetBytes(body);


            byte[] responseData = myClient.UploadData(Url, "POST", postData);//得到返回字符流  
            resultBody = Encoding.UTF8.GetString(responseData);//解码  


            return resultBody;
        }

        public static Access_Token GetOauth2_Access_Token(string code)
        {
            appKey = ConfigurationManager.AppSettings["WeixingAuthAppId"];
            appSecret = ConfigurationManager.AppSettings["WeixingAuthAppSecret"];
            //获取Access_Token对象
            string urlGetAccess_Token = baseUrl + "access_token?appid=" + appKey + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code";
            Kevin.Comm.Logger.Tracer.Info("urlGetAccess_Token" + urlGetAccess_Token);
            string resultBody = Utility.GetBody(urlGetAccess_Token, Encoding.UTF8);
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            Access_Token access_token = jsonSerializer.Deserialize<Access_Token>(resultBody);

            Kevin.Comm.Logger.Tracer.Info("access_token" + access_token.access_token);

            return access_token;
        }

        public static WinXinUserInfo GetUserInfo(Access_Token access_token)
        {
            //获取UserInfo对象
            string userInfoByOpenIdByToKen = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token.access_token + "&openid=" + access_token.openid;
            string resultBody = Utility.GetBody(userInfoByOpenIdByToKen, Encoding.UTF8);
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            WinXinUserInfo userInfo = jsonSerializer.Deserialize<WinXinUserInfo>(resultBody);

            return userInfo;
        }


        public static string GetAccess_Token()
        {
            var timeStamp = DateTimeHelper.GetWeixinDateTime(DateTime.Now).ToString();
            var token = ConfigurationManager.AppSettings["WeixinPortalToken"];
            var portal = ConfigurationManager.AppSettings["WeixinPortalName"];
            string nonce = "11235813";

            string signature = Senparc.Weixin.MP.CheckSignature.GetSignature(timeStamp, nonce, token);

            var tokenAddress = ConfigurationManager.AppSettings["WeixinPortalHost"]
                + "/WeixinAPI/GetAccessToken?portal={0}&signature={1}&timestamp={2}&nonce={3}";

            var url = string.Format(tokenAddress, portal, signature, timeStamp, nonce);
            try
            {
                string accessToken = Utility.GetBody(url, Encoding.UTF8);

                Kevin.Comm.Logger.Tracer.TraceLog("USE promotion code get accessToken: " + url, "Use Promotion Code", "PromotionCode", true);
                Kevin.Comm.Logger.Tracer.TraceLog("USE promotion code get accessToken: " + accessToken, "Use Promotion Code", "PromotionCode", true);

                return accessToken;
            }
            catch (Exception e)
            {
                Kevin.Comm.Logger.Tracer.TraceLog("USE promotion code get accessToken error: " + e.Message, "Use Promotion Code", "PromotionCode", true);
                return string.Empty;
            }
        }

        public static string GetJsAPI_Token()
        {

            var timeStamp = DateTimeHelper.GetWeixinDateTime(DateTime.Now).ToString();
            var token = ConfigurationManager.AppSettings["WeixinPortalToken"];
            var portal = ConfigurationManager.AppSettings["WeixinPortalName"];
            string nonce = "11235813";

            try
            {
                string signature = Senparc.Weixin.MP.CheckSignature.GetSignature(timeStamp, nonce, token);

                var tokenAddress = ConfigurationManager.AppSettings["WeixinPortalHost"]
                    + "/WeixinAPI/GetTicket?portal={0}&signature={1}&timestamp={2}&nonce={3}";

                var url = string.Format(tokenAddress, portal, signature, timeStamp, nonce);
                string ticket = Utility.GetBody(url, Encoding.UTF8);

                Kevin.Comm.Logger.Tracer.TraceLog("USE promotion code get Ticket: " + url, "Use Promotion Code", "PromotionCode", true);
                Kevin.Comm.Logger.Tracer.TraceLog("USE promotion code get Ticket: " + ticket, "Use Promotion Code", "PromotionCode", true);
                return ticket;
            }
            catch (Exception e)
            {
                Kevin.Comm.Logger.Tracer.TraceLog("USE promotion code get accessToken error: " + e.Message, "Use Promotion Code", "PromotionCode", true);
                return string.Empty;
            }
        }

        public static string GetJsAPI_Signature(string jsapi_ticket, string noncestr, string timestamp, string url)
        {
            var arr = new[] { "jsapi_ticket=" + jsapi_ticket, "noncestr=" + noncestr, "timestamp=" + timestamp, "url=" + url }
                .OrderBy(z => z[0]).ToArray();
            var arrString = string.Join("&", arr);

            //var enText = FormsAuthentication.HashPasswordForStoringInConfigFile(arrString, "SHA1");//使用System.Web.Security程序集
            var sha1 = System.Security.Cryptography.SHA1.Create();
            var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrString));
            StringBuilder enText = new StringBuilder();
            foreach (var b in sha1Arr)
            {
                enText.AppendFormat("{0:x2}", b);
            }

            return enText.ToString();
        }
    }
}
